package com.bupt.liutong.admin.bbs.bo;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.transaction.annotation.Transactional;

import com.bupt.liutong.admin.core.base.BaseBo;
import com.bupt.liutong.admin.bbs.dao.PostDao;
import com.bupt.liutong.admin.bbs.dto.Post;
import com.bupt.liutong.admin.bbs.form.PostForm;
import com.bupt.liutong.util.BeanUtils;
import com.bupt.liutong.util.DateUtils;

public class PostBo extends BaseBo {

	private PostDao postDao;

	public List<PostForm> getPostsByPage(PostForm postForm,
			HttpServletRequest request) {
		Post post = new Post();
		sm.pagingWithNoCriteria(postForm, post, "bbs_post.getPostsCount");
		List<Post> posts = postDao.getPostsByPage(post);
		return BeanUtils.dtoToForm(posts, PostForm.class);
	}

	public List<PostForm> getRepliesByPage(PostForm postForm,
			HttpServletRequest request) {
		Post post = new Post();
		sm.pagingWithNoCriteria(postForm, post, "bbs_post.getPostsCount");
		List<Post> posts = postDao.getRepliesByPage(post);
		return BeanUtils.dtoToForm(posts, PostForm.class);
	}

	public PostForm getPostById(PostForm postForm) {
		PostForm resultForm = new PostForm();
		Post post = postDao.getPostById(postForm.getId());
		BeanUtils.copyProperties(resultForm, post);
		return resultForm;
	}
	
	public void insertLzPost(PostForm postForm) {
		postForm.setParentId(new Long(-1));
		insertPost(postForm);
	}
	
	public void insertReply(PostForm postForm) {
		postForm.setTitle("");
		insertPost(postForm);
	}
	
	public void updateLastReplyTime(PostForm postForm) {
		postForm.setId(postForm.getParentId());
		postForm.setParentId(null);
		postForm.setLastReplyTime(DateUtils.getCurTime());
		updatePost(postForm);
		postForm.setParentId(postForm.getId());
		postForm.setId(null);
	}

	@Transactional
	private void insertPost(PostForm postForm) {
		postForm.setCreateTime(DateUtils.getCurTime());
		postForm.setLastReplyTime(DateUtils.getCurTime());
		Post post = new Post();
		BeanUtils.copyProperties(post, postForm);
		postDao.insertPost(post);
	}

	@Transactional
	public void updatePost(PostForm postForm) {
		Post post = new Post();
		BeanUtils.copyProperties(post, postForm);
		postDao.updatePost(post);
	}

	@Transactional
	public void deletePosts(String[] ids) {
		if (ids != null) {
			for (int i = 0; i < ids.length; i++) {
				postDao.deletePost(Long.parseLong(ids[i]));
			}
		}
	}

	public void setPostDao(PostDao postDao) {
		this.postDao = postDao;
	}
}
    
